package cn.tristenstudy.blog.controller;

import cn.tristenstudy.blog.pojo.dto.CommentDTO;
import cn.tristenstudy.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * 评论信息Controller
 *
 * @author xichen1.li
 * @date 2021-01-11 15:41
 */
@Controller
@RequestMapping("/comment")
public class CommentController {

    private static final int CONTENT_MAX_LENGTH = 100;
    private static final int NICK_NNAME_MAX_LENGTH = 10;

    @Autowired
    CommentService commentService;

    /**
     * 查询评论列表
     *
     * @param blogId 博客id
     * @param model  model
     * @return 评论页面
     */
    @GetMapping("/list/{blogId}")
    public String comments(@PathVariable Long blogId, Model model) {
        List<CommentDTO> commentList = commentService.listComment(blogId);
        model.addAttribute("comments", commentList);
        return "blog :: commentList";
    }

    /**
     * 新增评论信息
     *
     * @param commentDTO 评论信息
     * @return 评论页面
     */
    @PostMapping("/insert")
    public String insertComment(CommentDTO commentDTO, RedirectAttributes attributes) {
        String nickName = commentDTO.getNickName();
        String content = commentDTO.getContent();
        if (nickName.length() > NICK_NNAME_MAX_LENGTH) {
            attributes.addFlashAttribute("msg", "昵称长度不应超过10个字符！");
        } else if (content.length() > CONTENT_MAX_LENGTH) {
            attributes.addFlashAttribute("msg", "评论长度不应超过100个字符！");
        } else {
            commentService.insertComment(commentDTO);
        }
        return "redirect:/comment/list/" + commentDTO.getBlogId();
    }

}
